using System;
using OhioState.AssetManaged;
using OhioState.Graphics;
using OhioState.Graphics.Proxy;

namespace OhioState.Graphics.OpenGL
{
    public class ClippedDrawableHandler : OpenGLObject, IDrawable
    {
        private IDrawable drawable;
        private ClippedDrawableProxy clippedDrawableProxy;
        public ClippedDrawableHandler(ClippedDrawableProxy proxyObj): base(proxyObj)
        {
            clippedDrawableProxy = proxyObj;
            drawable = proxyObj.Drawable;
            _material = drawable.Material;
        }

        #region IDrawable Members

        IBoundingVolume IDrawable.BoundingVolume
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }

        private IMaterial _material;
        OhioState.Graphics.IMaterial IDrawable.Material
        {
            get { return  clippedDrawableProxy.Material; }
            set { _material = value; }
        }

        private IDrawable drawGL;
        void IDrawable.Render(IRenderPanel panel)
        {
            this.Update(panel);
            
            //First clip using the clip planes, then render the drawable
            ClipPlaneHandler cp1 = null, cp2 = null, cp3 = null;
            if (clippedDrawableProxy.ClipPlanes[0].Name != "NoClip")
            {
                cp1 = panel.ResourceManager.GetItem(clippedDrawableProxy.ClipPlanes[0] as IAssetManaged) as ClipPlaneHandler;
                cp1.Enable(0);
            }
            if (clippedDrawableProxy.ClipPlanes[1].Name != "NoClip")
            {
                cp2 = panel.ResourceManager.GetItem(clippedDrawableProxy.ClipPlanes[1] as IAssetManaged) as ClipPlaneHandler;
                cp2.Enable(1);
            }
            if (clippedDrawableProxy.ClipPlanes[2].Name != "NoClip")
            {
                cp3 = panel.ResourceManager.GetItem(clippedDrawableProxy.ClipPlanes[2] as IAssetManaged) as ClipPlaneHandler;
                cp3.Enable(2);

            }

            drawGL.Render(panel);
         
            if (clippedDrawableProxy.ClipPlanes[0].Name != "NoClip") 
                cp1.Disable(0);
            if (clippedDrawableProxy.ClipPlanes[1].Name != "NoClip") 
                cp2.Disable(1);
            if (clippedDrawableProxy.ClipPlanes[2].Name != "NoClip") 
                cp3.Disable(2);

        }

        public override void Update(IRenderPanel panel)
        {
            if (this.Invalid)
            {
                this.Invalid = false;
                drawable = clippedDrawableProxy.Drawable;
                drawGL = panel.ResourceManager.GetItem(drawable as IAssetManaged) as IDrawable;

                //Set the material for the drawable
                _material = clippedDrawableProxy.Material;

            }
        }
        #endregion
    }
}
 